﻿using Confluent.Kafka;
using Furion;
using Furion.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace furion.blog.Application.KafkaMQ.Producers
{
    public class WxSendMsgToMemberProducer : ISingleton, IDisposable
    {
        public static string TOPIC = "WX-SEND-MSG-TO-MEMBER";
        private IProducer<string, string> _producer;

        public WxSendMsgToMemberProducer()
        {
            if (this._producer == null)
            {
                var config = new ProducerConfig
                {
                    BootstrapServers = App.Configuration["Kafka:BootstrapServers"]
                };
                this._producer = new ProducerBuilder<string, string>(config).Build();
            }
        }

        /// <summary>
        /// 发送信息
        /// </summary>
        /// <typeparam name="TMessage"></typeparam>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task CreateAsync<TMessage>(TMessage message) where TMessage : class
        {
            await _producer.ProduceAsync(TOPIC, new Message<string, string>
            {
                Key = Guid.NewGuid().ToString(),
                Value = JsonConvert.SerializeObject(message) //message.SerializeToJson()
            });
        }

        public void Dispose()
        {
            _producer?.Dispose();
        }
    }
}
